package com.kkom1.tapeat;

import media_controller.MediaController;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.slidinglayer.SlidingLayer;

import data_management.PatternDataManager;
import data_management.PatternSet;
import data_management.SettingData;

public class MainActivity extends FragmentActivity {
	private Activity context;
	private PatternDataManager pdata;
	private SettingData sdata;
	private RelativeLayout ll; // Main Layout
	private RhythmPad rhythmPad;
	private TextView title;
	private TextView test;
	private ListView plist;
	private ListAdapter listadapter;
	
	private ToggleButton bt_padmode;
	private ToggleButton bt_settings;
	
	private void init() {
		context = this;
	
		// init fragment presenter
	//	FragmentPresenter.getInstance().setFragmentManager(getFragmentManager());
		
		// opening data
		pdata = PatternDataManager.getInstance();
		sdata = SettingData.getInstance();

		// Setting Layout
		ll = (RelativeLayout) findViewById(R.id.main_main);
		ll.setBackground(WallpaperManager.getInstance(context).getDrawable());

		// window size
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		// Pad setting
		rhythmPad = new RhythmPad(this, (int)(displayMetrics.widthPixels), sdata.timelimit());
		rhythmPad
		.setRes_Inner(R.drawable.pad_inner)
		.setRes_Outer(R.drawable.outer)
		.setRes_Pattern(R.drawable.arc)
		.setRes_Needle(R.drawable.pin);
		
		
		plist = (ListView)findViewById(R.id.main_plist);
        listadapter = new ListAdapter(
        		context,
        		R.layout.patternlayout, 
        		pdata.getList());
        LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );  
        FrameLayout ll = (FrameLayout)layoutInflater.inflate( R.layout.pad_part, null, false );
        plist.addHeaderView(ll);
        ll.addView(rhythmPad);
//        plist.addHeaderView(rhythmPad);
        Log.d("adapter:", ""+listadapter);
        plist.setAdapter(listadapter);
        
		// animation event handling
		rhythmPad.setOnEndListener(PAD_MODE_EVENT);
		
		// init option components
		init_option_components();
		
		// binding buttons
		bt_padmode = (ToggleButton)findViewById(R.id.bt_padmode);
		bt_settings = (ToggleButton)findViewById(R.id.bt_settings);
		
	} 
	
	// TOP Buttons' settings
	private boolean mode = ADD_MODE;
	private static final boolean ADD_MODE = true;
	private static final boolean PAD_MODE = false;
	
	private final RhythmPad.OnEventListener PAD_MODE_EVENT = new RhythmPad.OnEventListener() {
		public void go() {
			// dealing last pattern
			//rhythmPad.upLast();

			// set pattern to data to update
			PatternSet _new = rhythmPad.getPatternSet();
			PatternSet ps = pdata.match(_new, sdata.getSensitivity());

			// No pattern
			if (ps == null) {
				//rhythmPad.reset();
				//startActivity(new Intent(MainActivity.this, PListActivity.class));
				Toast.makeText(MainActivity.this, R.string.msg_FailedToFindPattern, 0).show();
				//finish();
				return;
			}
			MediaController.execute(context, ps.packageName(), ps.type());
			finish();
		}
	};
	
	private final RhythmPad.OnEventListener ADD_MODE_EVENT = new RhythmPad.OnEventListener() {
		public void go() {
			//rhythmPad.upLast();
			
			pdata.reset();
			boolean isExisted = pdata.setPatternUnit(rhythmPad.getPattern(), sdata.getSensitivity());
			Log.d("pattern set:", ""+rhythmPad.getPattern().size());
			Class c = null;
			if(isExisted){
				Toast.makeText(MainActivity.this, R.string.msg_DetectedSimilarPattern , 0).show();
				return ;
			}
			else {
				c = NickSettingActivity.class;
				Intent i = new Intent(MainActivity.this , c);
				startActivity(i);
				finish();
			}
		}
	};
	
	// option panel settings
	private SlidingLayer mSlidingLayer;
	private void initOptionPanel(){
		mSlidingLayer = (SlidingLayer) findViewById(R.id.optionPanelLayer);
		LayoutParams rlp = (LayoutParams) mSlidingLayer.getLayoutParams();
		mSlidingLayer.setStickTo(SlidingLayer.STICK_TO_RIGHT);
		rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		
		mSlidingLayer.setLayoutParams(rlp);
        mSlidingLayer.setShadowWidthRes(R.dimen.shadow_width);
        mSlidingLayer.setShadowDrawable(R.drawable.sidebar_shadow); 
        mSlidingLayer.setOffsetWidth(getResources().getDimensionPixelOffset(R.dimen.offset_width));
	}
	
    public void buttonClicked(View v) {
        switch (v.getId()) {
        
        	//for appearing option panel
        case R.id.bt_settings:
            if (!mSlidingLayer.isOpened()) {
                mSlidingLayer.openLayer(true);
            }
            else {
                mSlidingLayer.closeLayer(true);
            }
            break;
        
            // for pad mode
        case R.id.bt_padmode:
        	if(mode == ADD_MODE){
        		// code here for add mode
        		rhythmPad.setOnEndListener(ADD_MODE_EVENT);
        		rhythmPad.refresh();
        	}
        	else if(mode == PAD_MODE){
        		// code here for pad mode
        		rhythmPad.setOnEndListener(PAD_MODE_EVENT);
        		rhythmPad.refresh();
        	}
        	mode = !mode;
        	break;
        }
        
    }
    
    private void refresh_mode_buttons(){
    	if(mSlidingLayer.isOpened())
    		mSlidingLayer.closeLayer(true);
    	bt_padmode.setChecked(false);
    	bt_settings.setChecked(false);
    }
    
    public void onResume(){
    	super.onResume();
    	listadapter.notifyDataSetChanged();
    	refresh_option_components();
    	//refresh_mode_buttons();
    }
    
    private SeekBar sb_sensitivity;
    private ToggleButton tog_lock;
    private void refresh_option_components(){
    	tog_lock.setChecked(sdata.isLock_on());
    	sb_sensitivity.setProgress(sdata.getSensitivity());
    }
    
    private void init_option_components(){
    	sb_sensitivity = (SeekBar)findViewById(R.id.sensitivity_bar);
    	tog_lock = (ToggleButton)findViewById(R.id.tog_lockon);
    	
		tog_lock.setChecked(sdata.isLock_on());
		tog_lock.setOnCheckedChangeListener(
				new CompoundButton.OnCheckedChangeListener(){
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						sdata.setLock_on(isChecked);
						sdata.save();
						
						if(sdata.isLock_on() == true)
							startService(new Intent("com.kkom1.tapeat.services.lockservice"));
						else 
							stopService(new Intent("com.kkom1.tapeat.services.lockservice"));
					}
				});
		
		sb_sensitivity.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {
				sdata.setSensitivity(seekBar.getProgress());
				sdata.save();
			}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}
		});
    }

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		setContentView(R.layout.activity_main);

		init();
		initOptionPanel();

		// guide activity
		if (false) {
			Intent guide = new Intent(MainActivity.this, GuideActivity.class);
			startActivity(guide);
		}
	}

	// menu
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		// Toast.makeText(this, ""+item.getOrder(), 0).show();
		switch (item.getOrder()) {
		case 0:
			intent = new Intent(MainActivity.this, MainActivity.class);
			break;

		case 4:
			moveTaskToBack(true);
			finish();
			android.os.Process.sendSignal(android.os.Process.myPid(),
					android.os.Process.SIGNAL_KILL);
			return true;
		default:
			return false;
		}
		startActivity(intent);
		return true;
	}
}